package cn.da.shuai.cool.finance.controller;

import cn.da.shuai.cool.common.entity.R;
import cn.da.shuai.cool.finance.model.CoolAccountsReceivable;
import cn.da.shuai.cool.finance.service.ICoolAccountsReceivableService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/finance/accounts-receivable")
@Tag(name = "应收账款管理")
public class CoolAccountsReceivableController {

    @Autowired
    private ICoolAccountsReceivableService accountsReceivableService;

    @PostMapping("/record")
    @Operation(summary = "记录应收账款")
    public R<Boolean> recordReceivable(@RequestBody CoolAccountsReceivable receivable) {
        return R.ok(accountsReceivableService.recordReceivable(receivable));
    }

    @PostMapping("/payment")
    @Operation(summary = "记录付款")
    public R<Boolean> recordPayment(@RequestParam String invoiceNo, @RequestParam BigDecimal amount, @RequestParam String paymentReference) {
        return R.ok(accountsReceivableService.recordPayment(invoiceNo, amount, paymentReference));
    }

    @GetMapping("/overdue")
    @Operation(summary = "获取逾期应收账款")
    public R<List<CoolAccountsReceivable>> getOverdueReceivables() {
        return R.ok(accountsReceivableService.getOverdueReceivables());
    }

    @GetMapping("/aging-analysis")
    @Operation(summary = "获取账龄分析")
    public R<Map<String, Object>> getAgingAnalysis() {
        return R.ok(accountsReceivableService.getAgingAnalysis());
    }

    @GetMapping("/customer-balance")
    @Operation(summary = "获取客户余额")
    public R<BigDecimal> getCustomerBalance(@RequestParam Long customerId) {
        return R.ok(accountsReceivableService.getCustomerBalance(customerId));
    }

    @GetMapping("/trend")
    @Operation(summary = "获取应收账款趋势")
    public R<List<Map<String, Object>>> getReceivablesTrend(
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
        return R.ok(accountsReceivableService.getReceivablesTrend(startDate, endDate));
    }

    @PostMapping("/write-off")
    @Operation(summary = "应收账款核销")
    public R<Boolean> writeOff(@RequestParam String invoiceNo, @RequestParam String reason) {
        return R.ok(accountsReceivableService.writeOff(invoiceNo, reason));
    }

    @GetMapping("/collection-efficiency")
    @Operation(summary = "获取收款效率报告")
    public R<Map<String, Object>> getCollectionEfficiencyReport() {
        return R.ok(accountsReceivableService.getCollectionEfficiencyReport());
    }
}